package com.event.story;

import com.dto.AttentionDto;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.eventbus.Subscribe;
import com.handler.email.Email;
import com.handler.email.EmailHandler;
import com.mapper.self.AttentionMapper;
import com.mapper.self.CompanyMapper;
import com.mapper.self.SetMapper;
import com.pojo.ShCompany;
import com.pojo.ShSet;
import com.utils.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * Created by Huoyunren on 2016-09-07.
 */
@Component
public class StoryEventListener {

  private static final Logger LOG = LoggerFactory.getLogger(StoryEventListener.class);
  @Autowired
  private AttentionMapper attentionMapper;
  @Autowired
  private CompanyMapper companyMapper;
  @Autowired
  private EmailHandler emailHandler;
  @Autowired
  private SetMapper setMapper;

  @Subscribe
  public void work(StoryEvent storyEvent) {

    LOG.info("新文章邮件通知粉丝：{}", JsonUtils.JSON().toJson(storyEvent));
    mailNotify(storyEvent);
  }

  private void mailNotify(StoryEvent storyEvent) {
    List<AttentionDto> fans = attentionMapper.queryFans(storyEvent.getEmail());
    if (CollectionUtils.isEmpty(fans)) {
      return;
    }
    List<AttentionDto> needNotifyFans = filterNeedNotifyCompany(fans);
    if (CollectionUtils.isEmpty(needNotifyFans)) {
      return;
    }

//    List<String> needNotifyEmails = needNotifyFans.stream().map(new Function<AttentionDto, String>() {
//      @Override
//      public String apply(AttentionDto attentionDto) {
//        return attentionDto.getEmail();
//      }
//    }).collect(Collectors.toList());

    List<String> needNotifyEmails = Lists.newArrayList();
    for (AttentionDto needNotifyFan : needNotifyFans) {
      needNotifyEmails.add(needNotifyFan.getEmail());
    }
    ShCompany company = companyMapper.queryByEmail(storyEvent.getEmail());
    String alias = company.getName();
    if (StringUtils.isBlank(alias)) {
      alias = company.getEmail();
    }
    Email email = new Email();
    String subject = "关注动态:" + alias + "发布文章:" + storyEvent.getTitle();
    StringBuffer content = new StringBuffer();
    content.append("标题：");
    content.append(storyEvent.getTitle());
    content.append("\n");
    content.append("副标题：");
    content.append(storyEvent.getSubTitle());
    content.append("\n");
    content.append("查看详情：");
    content.append("http://liuyuanwai.cn/story/info?uuid=");
    content.append(storyEvent.getArticleUuid());
    content.append("\n");
    content.append("\n");
    content.append("提示:如果不想收到该邮件,你可以在个人设置中关闭提醒.但这样做可能会错过一些美好的事情.");
    email.setSubject(subject);
    email.setContent(content.toString());
    email.setEnableHtml(Boolean.FALSE);
    String[] array = (String[]) needNotifyEmails.toArray(new String[needNotifyEmails.size()]);
    email.setTo(array);
    emailHandler.asyncSendMail(email);
  }

  // - 过滤掉设置不提醒关注文章通知的用户
  private List<AttentionDto> filterNeedNotifyCompany(List<AttentionDto> fans) {
//    List<String> emailList = fans.stream().map(new Function<AttentionDto, String>() {
//      @Override
//      public String apply(AttentionDto attentionDto) {
//        return attentionDto.getEmail();
//      }
//    }).collect(Collectors.toList());

    List<String> emailList = Lists.newArrayList();
    for (AttentionDto fan : fans) {
      emailList.add(fan.getEmail());
    }
    List<ShSet> list = setMapper.list(emailList);
    if (CollectionUtils.isEmpty(list)) {
      return fans;
    }
    Map<String/* email */, Integer/* storyNotify */> map = Maps.newHashMap();
    for (ShSet shSet : list) {
      map.put(shSet.getEmail(), shSet.getAttentionNotify());
    }
    Iterator<AttentionDto> iterator = fans.iterator();
    while (iterator.hasNext()) {
      AttentionDto attentionDto = iterator.next();
      if (map.get(attentionDto.getEmail()).compareTo(0) == 0) {
        iterator.remove();
      }
    }
    return fans;
  }


}
